<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ################

class VMS_Client
{
    public function __construct(){
        $USER = JFX::registry('JFX_User');

        if(isset($USER->JFX_Module_Vms_Client_Conn)){
            $this->conn = $USER->JFX_Module_Vms_Client_Conn;
        }else{
            $this->conn = array();
        }
        
    }

    public function connect($connid){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $CRYPT = JFX::registry('JFX_Crypt');
        $connid = (int) $connid;
        $USER = JFX::registry('JFX_User');

        $cData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}vms_servers WHERE id = '{$connid}'");
        if(!is_array($cData) || count($cData) == 0) return false;
        $this->salt = $CRYPT->decrypt($cData['crypt_salt']);
        $res = $this->request($connid, $cData['url'].'/connect/', 
                array('username'=>$cData['username'], 'password'=>$CRYPT->decrypt($cData['pass']), 'lang'=>$USER->lang)
            );

        $res = unserialize($res);

        if(!is_object($res) || $res->result==='FAIL'){
            return false;
        }else{
            $this->conn[$connid] = $res->conn;
            $USER->JFX_Module_Vms_Client_Conn = $this->conn;
            return true;
        }

    }

    public function request($connid, $url, $params){
        $paramImp = array();
        if(array_key_exists($connid, $this->conn)) $params['conn'] = $this->conn[$connid];
        foreach($params as $k=>$v){
            $paramImp[] = urlencode($k).'='.urlencode($v);
        }
        $paramString = implode('&', $paramImp);

        if($this->salt !== ''){
            // using encryption
            $myCrypt = new JFX_Crypt($this->salt);
            $paramString = 'r='.$myCrypt->crypt($paramString);
            $url = (strpos($url, '?')===false)
                ? $url.'?'.$paramString
                : $url.'&'.$paramString
                ;
        }else{
            $url = (strpos($url, '?')===false)
                ? $url.'?'.$paramString
                : $url.'&'.$paramString
                ;
        }
        
        return file_get_contents($url);
    }

}